import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, IsNull, Not, Repository } from 'typeorm';
import { RejectReason } from './rejectReason.entity';
import { EnumRejectReasonType } from './rejectReason.enum';
import DataBase from 'src/config/database';

@Injectable()
export class RejectReasonService {
  constructor(
    @InjectRepository(RejectReason)
    private repository: Repository<RejectReason>,
  ) {}

  findAll(): Promise<RejectReason[]> {
    return this.repository.find();
  }

  findOne(id: any): Promise<RejectReason> {
    return this.repository.findOne(id);
  }

  async remove(id: number): Promise<void> {
    await this.repository.delete(id);
  }

  async create(cats: RejectReason): Promise<void> {
    await this.repository.save(cats);
  }

  async save(id: number, type: string, reason: string){
    if(id){
      return await this.repository.update({id: id},{reason: reason})
    }else{
      let rejectReason = new RejectReason()
      rejectReason.reason = reason.trim()
      rejectReason.type = this.getType(type)
      rejectReason.create_time = new Date()
      return await this.repository.insert(rejectReason)
    }
  }

  async save_batch(list){
    let insertList = list.filter(e => !e.id)
    let updateList = list.filter(e => e.id)
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      if(insertList.length > 0){
        let addList = []
        insertList.map(e => {
          let item = new RejectReason()
          item.create_time = new Date()
          item.reason = e.reason.trim()
          item.type = this.getType(e.type)
          addList.push(item)
        })
        await this.repository.createQueryBuilder(null, queryRunner)
          .insert()
          .into(RejectReason)
          .values(addList)
          .execute()
      }
      if(updateList.length > 0){
        let updateBatch = () => {
          return new Promise((resolve, reject) => {
            let max = updateList.length - 1
            updateList.map(async(e, index) => {
              let item = new RejectReason()
              item.id = e.id
              item.reason = e.reason.trim()
              await this.repository.createQueryBuilder(null, queryRunner).update({reason: e.reason}).where({id: e.id}).execute()
              if(max === index){
                resolve(true)
              }
            })
          })
        }
        updateBatch()
      }
      
      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  getType(typeStr){
    let type
    switch(typeStr){
      case 'question':
        type = EnumRejectReasonType.question
        break;
      case 'original':
        type = EnumRejectReasonType.original
        break;
      case 'original_overease':
        type = EnumRejectReasonType.original_overease
        break;
      case 'answer':
        type = EnumRejectReasonType.answer
        break;
      case 'refund':
        type = EnumRejectReasonType.refund
        break;
      case 'ic_info_platform':
        type = EnumRejectReasonType.ic_info_platform
        break;
    }
    return type
  }

  findAll_ByType(typeStr: string) : Promise<RejectReason[]> | [] {
    let type = this.getType(typeStr)
    if(type === undefined){
      return []
    }
    return this.repository.query(`
      select * from reject_reason
      where type = ? and reason is not null and reason != '' and reject_reason.key is null
    `,[type])
  }
}
